/*
 * 设置 vuex 存储用户信息及相关操作
 */
import { getData, setData, removeData } from '/@/utils/auth'

let copyUser = {
  user: {
    socketState: null,
    uid: '',
    token: '',
    userInfo: {},
    mainInfo: []
  }
}

if (getData('store')) {
  copyUser = Object.assign({}, copyUser, JSON.parse(getData('store')))
}

const user = {
  state: {
    socketState: null,
    uid: '',
    token: '',
    userInfo: {},
    mainInfo: {}
  },
  mutations: {
    SET_UID: (state, uid) => {
      state.uid = uid
      copyUser.user.uid = uid
    },
    SET_TOKEN: (state, token) => {
      state.token = token
      copyUser.user.token = token
    },
    SET_SOCKET: (state, socketState) => {
      state.socketState = socketState
      copyUser.user.socketState = socketState
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
      copyUser.user.userInfo = state.userInfo
    },
    SET_MAININFO: (state, mainInfo) => {
      state.mainInfo = mainInfo
      copyUser.user.mainInfo = state.mainInfo
    }
  },
  actions: {
    socketState({ commit }, socketState) {
      commit('SET_SOCKET', socketState)
      setData('store', JSON.stringify(copyUser))
    },
    setUid({ commit }, uid) {
      commit('SET_UID', uid)
      setData('store', JSON.stringify(copyUser))
    },
    setToken({ commit }, token) {
      commit('SET_TOKEN', token)
      setData('store', JSON.stringify(copyUser))
    },
    setUserInfo({ commit }, userInfo) {
      commit('SET_USERINFO', userInfo)
      setData('store', JSON.stringify(copyUser))
    },
    setMainInfo({ commit }, mainInfo) {
      commit('SET_MAININFO', mainInfo)
      setData('store', JSON.stringify(copyUser))
    },
    clearStore({ commit }) {
      commit('SET_SOCKET', null)
      commit('SET_TOKEN', '')
      commit('SET_UID', '')
      commit('SET_USERINFO', {})
      commit('SET_MAININFO', [])
      removeData('store')
      removeData('uid')
    }
  }
}

if (getData('store')) {
  user.state = Object.assign({}, user.state, JSON.parse(getData('store')).user)
}

export default user

